package android.theHead;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;


/* class is inspired by class 'RestClient' as taken from
 * http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
 * on 19-9-2010
 * and adapted
 */


public class PostData {
	
	private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

	public String connect(String url, List<NameValuePair> data){
		
		HttpClient httpclient = new DefaultHttpClient();  
	    HttpPost httppost = new HttpPost(url);
	    
	    Log.i("post", "connecting");
	  
	    try {  
	        httppost.setEntity(new UrlEncodedFormEntity(data));  
	  
	        // Execute HTTP Post Request  
	        HttpResponse response = httpclient.execute(httppost);
	        
	        Log.i("post", response.getStatusLine().toString());
	        
	        // get entity
	        HttpEntity entity = response.getEntity();
	        
	        String result = null;
	        
            if (entity != null) {
            	 
                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                result= convertStreamToString(instream);
                Log.i("post",result);
 
                // Closing the input stream will trigger connection release
                instream.close();
            }
            return result;
	        
	    } catch (ClientProtocolException e) {  
            Log.i("PostData:Client protocol",e.toString());
	    } catch (IOException e) {
	    	Log.i("PostData:IOException	",e.toString());
	    }
	    return null;
	}

}
